package com.hyt.it.ogt.kq.main.controller.bm;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson15.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.exception.annotation.ThrowsAdvice;
import com.hyt.it.ogt.kq.common.bm.utils.Constant;
import com.hyt.it.ogt.kq.common.gov.config.swagger.ApiVersionConstant;
import com.hyt.it.ogt.kq.service.bm.model.entity.OrderListVo;
import com.hyt.it.ogt.kq.service.bm.model.entity.StudentPayInfo;
import com.hyt.it.ogt.kq.service.bm.model.entity.StudentSubject;
import com.hyt.it.ogt.kq.service.bm.model.param.PayOrderListOrderParam;
import com.hyt.it.ogt.kq.service.bm.model.param.PayOrderRefundOrderListParam;
import com.hyt.it.ogt.kq.service.bm.model.vo.OrderInfoVo;
import com.hyt.it.ogt.kq.service.bm.model.vo.OrderParam;
import com.hyt.it.ogt.kq.service.bm.model.vo.PayListVo;
import com.hyt.it.ogt.kq.service.bm.model.vo.PayOrderProject;
import com.hyt.it.ogt.kq.service.bm.model.vo.Reconciliation;
import com.hyt.it.ogt.kq.service.bm.model.vo.ReconciliationList;
import com.hyt.it.ogt.kq.service.bm.model.vo.RefundComments;
import com.hyt.it.ogt.kq.service.bm.model.vo.RefundTaskList;
import com.hyt.it.ogt.kq.service.bm.model.vo.StudentSubjectVo;
import com.hyt.it.ogt.kq.service.bm.service.IPayOrderService;
import com.hyt.it.ogt.kq.service.bm.service.IProjectService;
import com.hyt.it.ogt.kq.service.bm.service.IStudentPayService;
import com.hyt.log.annotation.Log;
import com.hyt.loginfo.controller.BaseLoginController;
import com.hyt.model.PageParam;
import com.hyt.swagger.ApiVersion;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSort;
import io.swagger.annotations.ApiSort;
import lombok.extern.slf4j.Slf4j;

/**
 * 订单管理
 *
 * @author wangt
 * @Description:
 * @date: 2020年8月31日 上午10:46:01
 * @version: V1.0
 */
@Slf4j
@RestController
@Api(tags = "20.订单管理接口", value = "订单管理接口")
@ApiSort(value = 20)
@RequestMapping("/bm/order")
public class PayOrderController extends BaseLoginController {

    @Autowired
    IPayOrderService iPayOrderService;

    @Autowired
    IProjectService iProjectService;

    @Autowired
    private IStudentPayService iStudentPayService;

    @ApiOperation(value = "20.1.1 管理端：订单管理列表-报名任务列表", notes = "20000:成功")
    @ApiOperationSort(value = 1)
    @RequestMapping(value = "/listTask", method = RequestMethod.GET)
    public Object listTask(OrderParam param, PageParam<PayOrderProject> pageParam) {
        IPage<PayOrderProject> page = pageParam;

        page = iPayOrderService.queryProjectList(pageParam, param, getOfficeId());
        return ApiResponse.builder().code(Constant.RESPONSE_CODE_SUCCESS).data(page).build();
    }

    @ApiOperation(value = "20.1.2 管理端：订单管理列表",
            notes = "20000:成功；31201201：订单管理列表异常；",
            response = OrderListVo.class)
    @ApiOperationSort(value = 2)
    @ApiVersion(group = ApiVersionConstant.V2_4_10)
    @ThrowsAdvice(code = 31201201, print = "订单管理列表异常")
    @GetMapping(value = "/listOrder")
    public ApiResponse<IPage<OrderListVo>> listOrder(PayOrderListOrderParam pageParam) {
        pageParam.setDeptIds(getDeptIds());
        IPage<OrderListVo> page = iPayOrderService.querylistOrder(pageParam);
        return ApiResponse.<IPage<OrderListVo>>builder()
                .code(Constant.RESPONSE_CODE_SUCCESS)
                .data(page)
                .build();
    }

    @ApiOperation(value = "20.1.3 管理端：订单管理列表-退款", notes = "20000:成功")
    @ApiOperationSort(value = 3)
    @Log(module = "订单管理", business = "订单管理列表退款")
    @ThrowsAdvice(code = 31010125, print = "退款失败，请联系管理员！")
    @RequestMapping(value = "/refundManage", method = RequestMethod.GET)
    public ApiResponse<String> refundManage(String orderId, String subjectIds) {
        boolean flag = iPayOrderService.refundManage(orderId, subjectIds);
        if (flag) {
            return ApiResponse.<String>builder().code(Constant.RESPONSE_CODE_SUCCESS).data("退款成功！").build();
        } else {
            return ApiResponse.<String>builder().code(Constant.RESPONSE_CODE_31010125).data("退款失败，请联系管理员！").build();
        }
    }

    @ApiOperation(value = "20.1.4 管理端：订单管理列表- 查询订单详情", notes = "20000:成功")
    @ApiOperationSort(value = 4)
    @RequestMapping(value = "/queryOrderInfo", method = RequestMethod.GET)
    public Object queryOrderInfo(String orderId) {
        OrderInfoVo object = iPayOrderService.queryOrderInfo(orderId);
        return ApiResponse.builder().code(Constant.RESPONSE_CODE_SUCCESS).data(object).build();
    }

    @ApiOperation(value = "20.1.5 管理端：订单管理列表- 开发票", notes = "20000:成功")
    @ApiOperationSort(value = 5)
    @RequestMapping(value = "/queryInvoiceInfo", method = RequestMethod.GET)
    public Object queryInvoiceInfo(String orderId) {
        return ApiResponse.builder().code(Constant.RESPONSE_CODE_SUCCESS).data(null).build();
    }

    @ApiOperation(value = "20.1.6 管理端：退款申请-任务列表", notes = "20000:成功")
    @ApiOperationSort(value = 6)
    @ThrowsAdvice(code = 31201601, print = "退款申请任务列表查询失败")
    @RequestMapping(value = "/refundList", method = RequestMethod.GET)
    public Object refundList(OrderParam param, PageParam<RefundTaskList> pageParam) {
        IPage<RefundTaskList> page = pageParam;
        page = iPayOrderService.refundTaskList(pageParam, param, getOfficeId());
        return ApiResponse.builder().code(Constant.RESPONSE_CODE_SUCCESS).data(page).build();
    }

    @ApiOperation(value = "20.1.7 管理端：退款申请- 订单管理列表", notes = "20000:成功")
    @ApiOperationSort(value = 7)
    @ApiVersion(group = ApiVersionConstant.V2_4_10)
    @ThrowsAdvice(code = 31201701, print = "订单管理列表查询失败")
    @RequestMapping(value = "/refundOrderList", method = RequestMethod.GET)
    public ApiResponse<IPage<OrderListVo>> refundOrderList(PayOrderRefundOrderListParam pageParam) {
        pageParam.setDeptIds(getDeptIds());
        IPage<OrderListVo> page = iPayOrderService.refundOrderList(pageParam);
        return ApiResponse.<IPage<OrderListVo>>builder()
                .code(Constant.RESPONSE_CODE_SUCCESS)
                .data(page)
                .build();
    }

    @ApiOperation(value = "20.1.8 管理端：退款申请- 确认/拒绝（1：同意，2，：拒绝）", notes = "20000:成功")
    @ApiOperationSort(value = 8)
    @Log(module = "订单管理", business = "退款申请审批")
    @RequestMapping(value = "/refundComments", method = RequestMethod.POST)
    public Object refundComments(@RequestBody RefundComments refundComments) throws Exception {
        String msg = iPayOrderService.refundComments(refundComments);
        if ("14001".equals(msg)) {
            return ApiResponse.builder().code(Constant.RESPONSE_CODE_SUCCESS).data("退款操作成功！").build();
        } else {
            if(StrUtil.isNotBlank(msg)) {
                return ApiResponse.builder().code(Integer.valueOf(msg)).data("退款失败！").build();
            }else {
                return ApiResponse.builder().code(Constant.RESPONSE_CODE_31010126).data("退款失败！").build();
            }
        }
    }

    @ApiOperation(value = "20.1.9 管理端：订单管理列表- 查询科目列表-退款", notes = "20000:成功")
    @ApiOperationSort(value = 9)
    @RequestMapping(value = "/refundSubjectList", method = RequestMethod.GET)
    public Object refundSubjectList(String orderId) {
        List<StudentSubject> studentSubject = iPayOrderService.refundSubjectList(orderId);
        return ApiResponse.builder().code(Constant.RESPONSE_CODE_SUCCESS).data(studentSubject).build();
    }

    @ApiOperation(value = "20.1.9.1 根据项目查询可退款科目", notes = "20000:成功")
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "projectId", value = "项目id", dataType = "string", paramType = "query", required = true
            ),
            @ApiImplicitParam(
                    name = "studentId", value = "报考考生id", dataType = "string", paramType = "query", required = true
            )
    })
    @ApiOperationSort(value = 9)
    @RequestMapping(value = "/queryRefundSubjectListByProjectId", method = RequestMethod.GET)
    public ApiResponse<List<StudentSubjectVo>> queryRefundSubjectListByProjectId(String projectId, String studentId) {
        List<StudentSubjectVo> studentSubject = iPayOrderService.queryRefundSubjectListByProjectId(projectId, studentId);
        return ApiResponse.<List<StudentSubjectVo>>builder().code(Constant.RESPONSE_CODE_SUCCESS).data(studentSubject).build();
    }

    /**
     * 退款 回调地址（后台回调用）
     *
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "20.1.10  退款：第三方回调地址（后台回调用）", notes = "20000:成功")
    @ApiOperationSort(value = 10)
    @RequestMapping(value = "/refundNotifyUrl", method = RequestMethod.POST)
    public Object refundNotifyUrl(HttpServletRequest req, HttpServletResponse resp, String officeId, String id) throws IOException {
        Map<String, Object> payMap = iPayOrderService.refundNotifyUrl(req, officeId, id);
        log.info("refundNotifyUrl result:[{}]", JSON.toJSON(payMap));
        //return ApiResponse.builder().code(Constant.RESPONSE_CODE_SUCCESS).data(payMap).build();
        return "SUCCESS";
    }


    /**
     * 去缴费：查询缴费信息
     *
     * @return
     */
    @SuppressWarnings("unchecked")
    @ApiOperation(value = "20.1.11 管理端团体缴费 -去缴费：查询缴费列表信息", notes = "20000:成功,15038:重复支付，15042：考生未报名科目，，15043：缴费异常，")
    @ApiOperationSort(value = 11)
    @RequestMapping(value = "/queryPayInfoList", method = RequestMethod.GET)
    public Object queryPayInfoList(String studentIds) {
        Map<String, Object> map = iStudentPayService.queryPayInfoList(studentIds);

        if ("15038".equals(map.get("code"))) {
            return ApiResponse.builder().code(Constant.RESPONSE_CODE_31010127).data("考生60秒内重复缴费，请勿重新提交！").build();
        }
        if ("15043".equals(map.get("code"))) {
            return ApiResponse.builder().code(Constant.RESPONSE_CODE_31010128).data("缴费异常，请联系管理员 ！").build();
        }
        if ("15046".equals(map.get("code"))) {
            return ApiResponse.builder().code(Constant.RESPONSE_CODE_31010129).data("该项目设置不需要缴费！").build();
        }
        if ("15042".equals(map.get("code"))) {
            return ApiResponse.builder().code(Constant.RESPONSE_CODE_31010130).data("考生暂无需缴费科目或未审核通过，请勿重复缴费！").build();
        }

        List<StudentPayInfo> studentPayInfo = (List<StudentPayInfo>) map.get("data");
        return ApiResponse.builder().code(Constant.RESPONSE_CODE_SUCCESS).data(studentPayInfo).build();
    }

    /**
     * 去支付：跳转第三方支付页面进行支付
     *
     * @return
     */
    @ApiOperation(value = "20.1.12  去支付：跳转第三方支付页面进行支付 ", notes = "20000:成功")
    @ApiOperationSort(value = 12)
    @PostMapping(value = "/payList")
    @Log(module = "缴费管理", business = "管理端缴费去支付")
    @ThrowsAdvice(code = 31200112, print = "提交缴费订单异常，请联系系统管理员")
    public Object pay(@RequestBody PayListVo payListVo) {
        Map<String, Object> payMap = iStudentPayService.payList(payListVo);
        if (Boolean.valueOf(String.valueOf(payMap.get("flag")))) {
            return ApiResponse.builder().code(Constant.RESPONSE_CODE_SUCCESS).data(payMap).build();
        } else {
            return ApiResponse.builder().code(31200112).data(payMap).build();
        }
    }

    @ApiOperation(value = "20.1.13 管理端：退款列表-退款详情", notes = "20000:成功")
    @ApiOperationSort(value = 13)
    @RequestMapping(value = "/refundSubjectListDetail", method = RequestMethod.GET)
    public Object refundSubjectListDetail(String orderId) {
        List<StudentSubject> studentSubject = iPayOrderService.refundSubjectListDetail(orderId);
        return ApiResponse.builder().code(Constant.RESPONSE_CODE_SUCCESS).data(studentSubject).build();
    }

    @ApiOperation(value = "20.1.13 管理端：退款列表-退款详情", notes = "20000:成功")
    @ApiOperationSort(value = 13)
    @RequestMapping(value = "/refundSubjectListDetailV2", method = RequestMethod.GET)
    public Object refundSubjectListDetail(String orderId, String refundOrderId) {
        List<StudentSubject> studentSubject = iPayOrderService.refundSubjectListDetail(orderId);
        return ApiResponse.builder().code(Constant.RESPONSE_CODE_SUCCESS).data(studentSubject).build();
    }


    /**
     * 后台管理-机构对账-列表
     *
     * @param officeName
     * @param pageParam
     * @return
     */
    @ApiOperation(value = "20.1.14 后台管理-机构对账-列表", notes = "20000:成功")
    @ApiOperationSort(value = 14)
    @RequestMapping(value = "/officeReconciliation", method = RequestMethod.GET)
    public Object officeReconciliation(String officeName, PageParam<Reconciliation> pageParam) {
        IPage<Reconciliation> page = pageParam;
        page = iPayOrderService.officeReconciliation(pageParam, officeName);
        return ApiResponse.builder().code(Constant.RESPONSE_CODE_SUCCESS).data(page).build();
    }


    /**
     * 后台管理-机构对账-机构下的任务明细
     *
     * @param pageParam
     * @return
     */
    @ApiOperation(value = "20.1.15 后台管理-机构对账-机构下的任务明细", notes = "20000:成功")
    @ApiOperationSort(value = 15)
    @RequestMapping(value = "/officeReconciliationList", method = RequestMethod.GET)
    public Object officeReconciliationList(
            String officeId, String orderId,
            String projectId, String date, String orderType,
            String payType, PageParam<ReconciliationList> pageParam) {
        IPage<ReconciliationList> page = pageParam;
        page = iPayOrderService.officeReconciliationList(pageParam, orderId, projectId, date, orderType, payType, officeId);
        return ApiResponse.builder().code(Constant.RESPONSE_CODE_SUCCESS).data(page).build();
    }

    /**
     * 后台管理-机构对账-查询机构下所有任务
     *
     * @return
     */
    @ApiOperation(value = "20.1.16 查询机构下所有任务", notes = "20000:成功")
    @ApiOperationSort(value = 16)
    @RequestMapping(value = "/officeProjectList", method = RequestMethod.GET)
    public Object officeProjectList(String officeId) {
        return ApiResponse.builder().code(Constant.RESPONSE_CODE_SUCCESS)
                .data(iPayOrderService.officeProjectList(officeId)).build();
    }


    /**
     * 退款 回调地址（后台回调用）
     *
     * @return
     * @throws Exception 
     */
    @ApiOperation(value = "20.2.1  易宝支付退款：第三方回调地址（后台回调用）", notes = "20000:成功")
    @ApiOperationSort(value = 10)
    @RequestMapping(value = "/yopRrefundNotifyUrl", method = RequestMethod.GET, produces = "text/plain")
    public Object yopRrefundNotifyUrlGet(HttpServletRequest req, HttpServletResponse resp, String officeId, String id) throws Exception {
        String response = req.getParameter("response");
        log.info("poynotifyUrl response:[{}], officeId:{}, id:{}", response, officeId, id);
        String customerIdentification = req.getParameter("customerIdentification");
        log.info("poynotifyUrl customerIdentification:[{}]", customerIdentification);
        String orderJson = iPayOrderService.analysisYopNotifyStr(response, officeId);
        if(StrUtil.isBlankIfStr(orderJson)) {
            return "FAIL";
        }
        log.info("poynotifyUrl orderJson:[{}]", orderJson);
        if(StrUtil.isBlankIfStr(orderJson)) {
            return "FAIL";
        }
        Map<String, Object> payMap = iPayOrderService.yopRrefundNotifyUrl(customerIdentification, orderJson, id);
        log.info("yopRrefundNotifyUrlGet result:[{}]", JSON.toJSON(payMap));
        return "SUCCESS";
    }

    /**
     * 退款 回调地址（后台回调用）
     *
     * @return
     * @throws Exception 
     */
    @ApiOperation(value = "20.2.2  易宝支付退款：第三方回调地址（后台回调用）", notes = "20000:成功")
    @ApiOperationSort(value = 10)
    @RequestMapping(value = "/yopRrefundNotifyUrl", method = RequestMethod.POST, produces = "text/plain")
    public Object yopRrefundNotifyUrlPost(HttpServletRequest req, HttpServletResponse resp, String officeId, String id) throws Exception {
        String response = req.getParameter("response");
        log.info("poynotifyUrl response:[{}], officeId:{}, id:{}", response, officeId, id);
        String customerIdentification = req.getParameter("customerIdentification");
        log.info("poynotifyUrl customerIdentification:[{}]", customerIdentification);
        String orderJson = iPayOrderService.analysisYopNotifyStr(response, officeId);
        if(StrUtil.isBlankIfStr(orderJson)) {
            return "FAIL";
        }
        log.info("poynotifyUrl orderJson:[{}]", orderJson);
        if(StrUtil.isBlankIfStr(orderJson)) {
            return "FAIL";
        }
        Map<String, Object> payMap = iPayOrderService.yopRrefundNotifyUrl(customerIdentification, orderJson, id);
        log.info("yopRrefundNotifyUrlGet result:[{}]", JSON.toJSON(payMap));
        return "SUCCESS";
    }
}
